<template>
  <div class="content-section messages-section">
    <div class="section-header">
      <h2 class="section-title">消息中心</h2>
      <div class="message-actions">
        <button class="btn-mark-all" @click="handleMessageRead">全部已读</button>
        <button class="btn-clear" @click="handleMessageDelete">清空消息</button>
      </div>
    </div>
    <div class="message-tabs">
      <div
        v-for="tab in messageTabs"
        :key="tab.key"
        :class="['message-tab', { active: activeMessageTab === tab.key }]"
        @click="handleTab(tab.key)"
      >
        <n-icon
          size="18"
          :component="
            tab.key === '1' ? LikeFilled : tab.key === '0' ? ChatbubbleEllipses : ChatbubblesSharp
          "
        />
        <span class="tab-label">{{ tab.label }}</span>
        <span class="badge" v-if="tab.count">{{ tab.count }}</span>
      </div>
    </div>
    <div class="message-list" ref="messageList" @scroll="handleScroll">
      <div v-for="message in dataList" :key="message.id" class="message-item">
        <div class="message-avatar-container">
          <img
            :src="message.avatar || websiteConfig.userImage"
            :alt="message.user"
            class="message-avatar"
          />
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="message-user">{{ message.senderName }}</span>
            <span class="message-time">{{ message.createTime }}</span>
          </div>
          <p class="message-text">{{ message.content }}</p>
        </div>
      </div>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 到底提示 -->
      <div v-if="isLastPage && dataList.length > 10" class="end-tip">
        <span>已经到底了</span>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && dataList.length === 0" class="empty-state"> 暂无消息 </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import {
    getMessageListApi,
    getMessageNumberApi,
    messageAllReadApi,
    messageAllReadByTypeApi,
    messageAllDeleteApi,
  } from '@/api/course';
  import { LikeFilled } from '@vicons/antd';
  import { ChatbubbleEllipses, ChatbubblesSharp } from '@vicons/ionicons5';
  import { ref, onMounted } from 'vue';
  import { websiteConfig } from '@/config/website.config';
  import { useMessage } from 'naive-ui';

  const message = useMessage();

  // ==================== 响应式数据 ====================
  const activeMessageTab = ref('0');

  const messageList = ref(null);

  // 消息相关
  const messageTabs = ref([
    { key: '0', label: '评论', count: 0 },
    { key: '1', label: '点赞', count: 0 },
    { key: '2', label: '关注', count: 0 },
  ]);

  async function getMessageNumber() {
    try {
      const data: any = await getMessageNumberApi();
      messageTabs.value[0].count = data[0];
      messageTabs.value[1].count = data[1];
      messageTabs.value[2].count = data[2];
    } catch (error) {
      console.error('error:', error);
    }
  }

  function handleTab(key: any) {
    activeMessageTab.value = key;
    resetPage();
    loadData(true);
    handleMessageReadByType(key);
  }

  const handleMessageRead = async () => {
    try {
      await messageAllReadApi();
      messageTabs.value[0].count = 0;
      messageTabs.value[1].count = 0;
      messageTabs.value[2].count = 0;
      console.log(`✅ 全部已读`);
    } catch (error) {
      console.error('❌ 已读失败', error);
    }
  };

  const handleMessageReadByType = async (key: any) => {
    if (messageTabs.value[key].count === 0) return;
    try {
      await messageAllReadByTypeApi(key);
      messageTabs.value[key].count = 0;
      console.log(`✅ 全部已读`);
    } catch (error) {
      console.error('❌ 已读失败', error);
    }
  };

  const handleMessageDelete = async () => {
    try {
      await messageAllDeleteApi();
      resetPage();
      loadData(true);
      message.success('消息已清空');
    } catch (error) {
      console.error('❌ 清空失败', error);
    }
  };

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const dataList = ref<any[]>([]);

  async function loadData(isRefresh = false) {
    if (loading.value || (isLastPage.value && !isRefresh)) return;

    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        type: activeMessageTab.value,
      };

      const data: any = await getMessageListApi(params);

      let list = data.records || [];

      if (isRefresh) {
        dataList.value = list;
      } else {
        dataList.value = [...dataList.value, ...list];
      }

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    dataList.value = [];
  }

  // 处理滚动事件
  const handleScroll = () => {
    if (!messageList.value) return;

    const { scrollTop, scrollHeight, clientHeight } = messageList.value;

    // 当滚动到距离底部50px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadData();
    }
  };

  onMounted(() => {
    getMessageNumber();
    resetPage();
    loadData(true);
  });
</script>

<style lang="less">
  // 消息中心样式
  .message-actions {
    display: flex;
    gap: 12px;

    .btn-mark-all,
    .btn-clear {
      background: #f8fafc;
      color: #64748b;
      border: 1px solid #e2e8f0;
      padding: 8px 16px;
      border-radius: 6px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: #f1f5f9;
        border-color: #cbd5e1;
      }
    }
  }

  .message-tabs {
    display: flex;
    margin-bottom: 24px;
    border-bottom: 1px solid #e2e8f0;

    .message-tab {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 20px;
      cursor: pointer;
      border-bottom: 2px solid transparent;
      transition: all 0.3s;
      color: #64748b;
      position: relative;

      &:hover {
        color: #d174df;
        background: rgba(209, 116, 223, 0.05);
      }

      &.active {
        color: #d174df;
        border-bottom-color: #d174df;
        background: rgba(209, 116, 223, 0.1);
      }

      .tab-icon {
        font-size: 16px;
      }

      .tab-label {
        line-height: 20px;
      }

      .badge {
        background: #ef4444;
        color: white;
        font-size: 12px;
        border-radius: 20px;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
      }
    }
  }

  .message-list {
    max-height: 620px;
    overflow-y: auto;
    padding-right: 8px;

    .message-item {
      display: flex;
      align-items: flex-start;
      padding: 16px;
      border-bottom: 1px solid #f1f5f9;
      transition: all 0.3s ease;

      &:hover {
        background: #f8fafc;
      }

      &:last-child {
        border-bottom: none;
      }

      .message-avatar-container {
        position: relative;
        margin-right: 16px;

        .message-avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid #e2e8f0;
        }
      }

      .message-content {
        flex: 1;

        .message-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 6px;

          .message-user {
            font-weight: 600;
            color: #1e293b;
            font-size: 14px;
          }

          .message-time {
            font-size: 12px;
            color: #64748b;
          }
        }

        .message-text {
          color: #374151;
        }
      }
    }
  }
</style>
